// svg代码转svg文件
import React, { useState, useRef } from "react";
import { Input, Button, Space, Card, message, Divider } from "antd";
import { DownloadOutlined } from "@ant-design/icons";
import ToolTitle from "@/components/ToolTitle";
import { imgToolsData } from "@/components/ToolsData";

const { TextArea } = Input;

const SvgCodeToSvgFile = () => {
  const [svgCode, setSvgCode] = useState<string>("");
  const [previewSrc, setPreviewSrc] = useState<string>("");
  const previewRef = useRef<HTMLDivElement>(null);

  // 处理SVG代码输入变化
  const handleSvgCodeChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setSvgCode(e.target.value);
  };

  // 预览SVG
  const handlePreview = () => {
    if (!svgCode.trim()) {
      message.error("请输入SVG代码");
      return;
    }

    try {
      const blob = new Blob([svgCode], { type: "image/svg+xml" });
      const url = URL.createObjectURL(blob);
      setPreviewSrc(url);
    } catch (error) {
      console.log(error);
      message.error("SVG代码有误，请检查");
    }
  };

  // 下载SVG文件
  const downloadSvg = () => {
    if (!svgCode.trim()) {
      message.error("请先输入SVG代码");
      return;
    }

    const blob = new Blob([svgCode], { type: "image/svg+xml" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "download.svg";
    a.click();
    URL.revokeObjectURL(url);
    message.success("SVG文件下载成功");
  };

  // 下载PNG文件
  const downloadPng = () => {
    if (!previewRef.current || !previewSrc) {
      message.error("请先预览SVG");
      return;
    }

    const svgElement = previewRef.current.querySelector("svg");
    if (!svgElement) {
      message.error("无法获取SVG元素");
      return;
    }

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();

    img.onload = () => {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx?.drawImage(img, 0, 0);

      const pngUrl = canvas.toDataURL("image/png");
      const a = document.createElement("a");
      a.href = pngUrl;
      a.download = "download.png";
      a.click();
      message.success("PNG文件下载成功");
    };

    img.src = previewSrc;
  };

  // 展示示例
  const showExample = (exampleNum: number) => {
    const examples = [
      '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/></svg>',
      '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 100 100"><rect x="10" y="10" width="80" height="80" fill="blue" /></svg>',
    ];

    setSvgCode(examples[exampleNum - 1]);
  };

  return (
    <div style={{ maxWidth: "1200px", margin: "0 auto", padding: "20px" }}>
      <ToolTitle
        title={
          imgToolsData.find((item) => item.title === "svg预览与下载")?.title ||
          ""
        }
        description={
          imgToolsData.find((item) => item.title === "svg预览与下载")
            ?.description || ""
        }
      />
      <Divider />

      <Space style={{ marginBottom: "20px" }}>
        <Button type="default" onClick={() => showExample(1)}>
          示例 1
        </Button>
        <Button type="default" onClick={() => showExample(2)}>
          示例 2
        </Button>
      </Space>

      <Card title="SVG代码" bordered={false}>
        <TextArea
          rows={10}
          value={svgCode}
          onChange={handleSvgCodeChange}
          placeholder="请输入SVG代码..."
        />

        <div style={{ marginTop: "20px", textAlign: "center" }}>
          <Space>
            <Button type="primary" onClick={handlePreview}>
              预览
            </Button>
            <Button icon={<DownloadOutlined />} onClick={downloadSvg}>
              下载SVG
            </Button>
            <Button icon={<DownloadOutlined />} onClick={downloadPng}>
              下载PNG
            </Button>
          </Space>
        </div>
      </Card>

      {/* {previewSrc && ( */}
      <>
        <Divider />
        <Card title="SVG预览" bordered={false}>
          <div
            className="w-full"
            ref={previewRef}
            style={{
              minHeight: "200px",
              display: "flex",
              justifyContent: "center",
              background:
                'url("")',
            }}
            dangerouslySetInnerHTML={{ __html: svgCode }}
          />
        </Card>
      </>
      {/* )} */}
    </div>
  );
};

export default SvgCodeToSvgFile;
